package svc

import (
	"go-weixin/app/order/api/internal/config"
	"go-weixin/common/chendb"
	"go-weixin/common/chendb/xorms"

	"github.com/smartwalle/alipay/v3"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
)

type ServiceContext struct {
	Config       config.Config
	AlipayClient *alipay.Client
	ChenDb       *chendb.ChenDb
	ChenCache    *redis.Redis
}

func NewServiceContext(c config.Config) *ServiceContext {
	client, err := alipay.New(c.AppId, c.PrivateKey, false)
	if err != nil {
		logx.Error("初始化支付宝失败", err)
	}

	// 加载证书
	if err := client.LoadAliPayPublicKey(c.PublicKey); err != nil {
		logx.Error("公钥加载错误", err)
	}

	chenDb := xorms.NewXormsDb(c.Mysql.Username, c.Mysql.Password, c.Mysql.Host, c.Mysql.Port, c.Mysql.Databases, c.Mysql.Showsql, c.Mysql.Migrate, c.Name)
	chenCache := redis.MustNewRedis(redis.RedisConf{
		Host: c.Cache.Host,
		Pass: c.Cache.Pass,
		Type: c.Cache.Type,
	})
	return &ServiceContext{
		Config:       c,
		AlipayClient: client,
		ChenDb:       chenDb,
		ChenCache:    chenCache,
	}
}
